package com.ruoyi.user.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUserUtils;
import com.ruoyi.user.domain.UserReceivingBank;
import com.ruoyi.user.mapper.UserReceivingBankMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 收款方式-银行Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-10
 */
@Service
public class UserReceivingBankService {
    @Autowired
    private UserReceivingBankMapper userReceivingBankMapper;

    /**
     * 查询收款方式-银行
     *
     * @param accountId 收款方式-银行主键
     * @return 收款方式-银行
     */
    public UserReceivingBank selectUserReceivingBankByAccountId(Long accountId) {
        return userReceivingBankMapper.selectUserReceivingBankByAccountId(accountId);
    }

    /**
     * 查询收款方式-银行列表
     *
     * @param userReceivingBank 收款方式-银行
     * @return 收款方式-银行
     */
    public List<UserReceivingBank> selectUserReceivingBankList(UserReceivingBank userReceivingBank) {
        return userReceivingBankMapper.selectUserReceivingBankList(userReceivingBank);
    }

    /**
     * 新增收款方式-银行
     *
     * @param userReceivingBank 收款方式-银行
     * @return 结果
     */
    public int insertUserReceivingBank(UserReceivingBank userReceivingBank) {
        userReceivingBank.setCreateTime(DateUtils.getNowDate());
        return userReceivingBankMapper.insertUserReceivingBank(userReceivingBank);
    }

    /**
     * 修改收款方式-银行
     *
     * @param userReceivingBank 收款方式-银行
     * @return 结果
     */
    public int updateUserReceivingBank(UserReceivingBank userReceivingBank) {
        userReceivingBank.setUpdateTime(DateUtils.getNowDate());
        return userReceivingBankMapper.updateUserReceivingBank(userReceivingBank);
    }

    /**
     * 批量删除收款方式-银行
     *
     * @param accountIds 需要删除的收款方式-银行主键
     * @return 结果
     */
    public int deleteUserReceivingBankByAccountIds(Long[] accountIds) {
        long userId = SecurityUserUtils.getUserId();
        // 校验地址是否为当前用户
        List<UserReceivingBank> list = userReceivingBankMapper.selectByIds(Arrays.asList(accountIds));
        boolean hasOtherUser = list.stream().anyMatch(userAddress -> !userAddress.getUserId().equals(userId));
        if (hasOtherUser) {
            throw new ServiceException("删除的收款账户不是当前用户的，无法删除");
        }
        return userReceivingBankMapper.deleteUserReceivingBankByAccountIds(accountIds);
    }
}
